package com.example.piece.ui.adapter

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RequestCode
import com.example.piece.constant.RoutePath
import com.example.piece.entity.Picture
import com.example.base.aop.click.RepeatClick
import com.example.base.ext.navigationTo
import com.example.base.ext.setCircleCropImageUrl
import com.example.base.ext.setCornersImageUrl
import com.example.piece.imageengine.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener

/**
 * 附件列表 Adapter
 * @param data 数据集合
 * @param isEditMode 是否为编辑模式, 编辑模式下可以进行条目的修改删除
 * @param isShowAddItem 在编辑模式下, 是否显示添加按钮, 当 isEditMode 为 false 时, 该参数无效
 * @param rv Adapter 的 RecyclerView, 默认为空
 * @param autoShowAddItem 是否自动显示添加按钮, 默认为显示, 当 isShowAddItem 为 false 时，该参数才生效
 * @param maxSize 最大附件数量, 默认是12
 * **/
class AnnexAdapter(
    data: ArrayList<Picture> = arrayListOf(),
    private var isEditMode: Boolean,
    private var isShowAddItem: Boolean,
    val rv: RecyclerView? = null,
    private val autoShowAddItem: Boolean = true,
    public val maxSize: Int = 12
) :
    BaseQuickAdapter<Picture, BaseViewHolder>(R.layout.adapter_annex_content, data) {

    init {
        // 编辑模式下, 默认追加一个添加按钮
        if (isEditMode and isShowAddItem) {
            requireNotNull(rv) {
                "In edit mode, you must set the RecyclerView of params rv"
            }
            data.add(Picture())
        }
    }

    override fun convert(helper: BaseViewHolder, item: Picture) {
        val isLastNode = helper.layoutPosition == data.size - 1

        // 设置图片
        val ivBox = helper.getView<AppCompatImageView>(R.id.ivBox)
        ivBox.visibility =
            if (isEditMode && isShowAddItem && isLastNode) View.GONE else View.VISIBLE
        ivBox.setCornersImageUrl(
            if (item.isVideo) item.cover else item.url, 1
        )

        // 背景色块
        val vPlay = helper.getView<View>(R.id.viewPlay)
        vPlay.visibility =
            if (isEditMode && isShowAddItem && isLastNode) View.GONE else {
                if (item.isVideo) View.VISIBLE else View.GONE
            }

        // 添加按钮
        val ivPlus = helper.getView<AppCompatImageView>(R.id.ivPlus)
        ivPlus.visibility =
            if (isEditMode && isShowAddItem && isLastNode) View.GONE else {
                if (item.isVideo) View.VISIBLE else View.GONE
            }

        // 删除按钮
        val ivDelete = helper.getView<AppCompatImageView>(R.id.ivDelete)
        ivDelete.visibility = if ((isEditMode && !isLastNode) || (!isShowAddItem && isEditMode))
            View.VISIBLE else View.INVISIBLE
        ivDelete.setOnClickListener {
            onClickDelete(item)
        }

        // 添加按钮
        val ivAdd = helper.getView<AppCompatImageView>(R.id.ivAdd)
        ivAdd.visibility =
            if (isEditMode && isShowAddItem && isLastNode) View.VISIBLE else View.GONE
        ivAdd.setOnClickListener {
            onClickAdd(ivAdd)
        }

        // 整个 Item 点击
        val cvRoot = helper.getView<CardView>(R.id.cvRoot)
        cvRoot.setOnClickListener {
            onClickItem(item)
        }
    }

    /**  根据不同的模式自动进行添加操作  **/
    override fun addData(itemData: Picture) {
        if (isEditMode and isShowAddItem) addData(data.size - 1, itemData)
        else super.addData(itemData)
        rv?.requestLayout()
    }

    /**  当点击条目时回调, 参数为当前 Item 的对应数据实体对象  **/
    @RepeatClick
    fun onClickItem(itemData: Picture) {
        // Log.e("AnnexAdapter", "clickItem")
        val index = data.indexOf(itemData)

        val sendData = arrayListOf<Picture>()
        sendData.addAll(data)
        if (isEditMode and isShowAddItem) {
            sendData.removeAt(data.size - 1)
        }
      //  changePhoto()
      /*  navigationTo(
            RoutePath.MAIN_PICTURE, mutableMapOf(
                Key.DataKey.PICTURES to sendData,
                Key.DataKey.SELECTED_INDEX to index
            )
        )*/
    }

    //更换头像
    @RepeatClick
    fun changePhoto() {
        PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())
            .setMaxSelectNum(maxSize-data.size)
            .setImageEngine(GlideEngine.createGlideEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    if (result != null && result.size > 0) {
                      //  mCenterViewBinding?.imgHead?.setCircleCropImageUrl(result.get(0)?.availablePath)
                        for (it in result){
                            val picture = it?.availablePath?.let { Picture(it, it, false) }
                            picture?.let { this@AnnexAdapter.addData(it) }

                            // 检测最大附件上传数
                            if (this@AnnexAdapter.itemCount - 1 >= maxSize)
                                setShowAddItem(false)
                        }

                    }
                }

                override fun onCancel() {}
            })
    }

    /**  异常附件结果提供  **/
    fun providerAnnex(): List<Picture> {
        val resultData = ArrayList(data)
        if (isEditMode and isShowAddItem)
            resultData.removeAt(resultData.size - 1)
        return resultData
    }

    /**  是否存在附件  **/
    fun hasAnnex(): Boolean = providerAnnex().isNotEmpty()

    /**  添加按钮的监听事件  **/
    private var onAddClickListener: View.OnClickListener? = null

    /**  绑定添加按钮的监听事件  **/
    fun bindAddClickListener(onAddClickListener: View.OnClickListener) {
        this.onAddClickListener = onAddClickListener
    }

    /**  元素删除的回调  **/
    private var onDeleteListener: (deletedPicture: Picture) -> Unit = {}

    /**  绑定元素删除的回调事件  **/
    fun bindDeleteListener(listener: (deletedPicture: Picture) -> Unit) {
        onDeleteListener = listener
    }

    /**  当点击添加条目时回调  **/
    @RepeatClick
    fun onClickAdd(view: View) {
        onAddClickListener?.onClick(view)
    }

    /**  当点击删除条目时回调, 参数为当前的 Item 对应数据实体对象  **/
    @RepeatClick
    fun onClickDelete(itemData: Picture) {
        // 执行 删除 Item 的操作, 并刷新 Ui 和当前储存的数据
        // Log.e("AnnexAdapter", "clickDelete")
        val index = data.indexOf(itemData)
        notifyItemRemoved(index)
        data.remove(itemData)
        rv?.requestLayout()
        onDeleteListener(itemData)

        // 检测最大附件上传数量
        if (isShowAddItem.not() and (itemCount < maxSize) and autoShowAddItem) {
            data.add(Picture())
            setShowAddItem(true)
        }
    }

    /**  设置编辑模式  **/
    public fun setShowAddItem(isShow: Boolean) {
        isShowAddItem = isShow

        if (isShow.not()) {
            data.removeAt(itemCount - 1)
            rv?.requestLayout()
        }
        this@AnnexAdapter.notifyDataSetChanged()
    }

    /**  处理 Activity 返回事件  **/
    fun processorActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        // 当拍照成功时, 获取照片的参数并添加到 Adapter 中
        if ((resultCode == Activity.RESULT_OK) and (requestCode == RequestCode.REQUEST_RECORDING)) {
            data?.apply {
                val isVideo = this.getBooleanExtra(Key.DataKey.IS_VIDEO, false)
                val cover = this.getStringExtra(Key.DataKey.COVER_PATH) ?: ""
                val url =
                    if (isVideo)
                        this.getStringExtra(Key.DataKey.VIDEO_PATH) ?: ""
                    else
                        this.getStringExtra(Key.DataKey.IMAGE_PATH) ?: ""

                val picture = Picture(url, cover, isVideo)
                this@AnnexAdapter.addData(picture)

                // 检测最大附件上传数
                if (this@AnnexAdapter.itemCount - 1 >= maxSize)
                    setShowAddItem(false)
            }
        }


        /*if (requestCode == Const.CODE_REQUEST_MEDIA) {
            val data = MediaSelector.obtainMediaFile(data)
            if (data != null) {
                for (d in data) {
                    var cover = ""
                    if (d.isVideo) {
                        var file: File
//                        var retriever = MediaMetadataRetriever();
//
//                        //转换路径 不然setdatasource 报错
//
//                        var str = d.filePath;
//                        var dataStr = str?.split("/");
//                        var fileTruePath = "/sdcard";
//                        if (dataStr != null) {
//                            for (i in 4 until dataStr.size) {
//                                fileTruePath = fileTruePath + "/" + dataStr[i]
//                            }
//
//                        }
//
//                        try {
//                            retriever.setDataSource(fileTruePath, HashMap());
//
////获得第10帧图片 这里的第一个参数 以微秒为单位
//                            var bitmap = retriever.getFrameAtTime(
//                                1000,
//                                MediaMetadataRetriever.OPTION_CLOSEST_SYNC
//                            );
//
//                            d.folderPath?.let { bitmap?.saveTo(it, d.fileName + "_cover.jpg") }
//
//                        } catch (e: Exception) {
//                                        Log.e("TAGTAGTAGTAG", "dateDiffer: "+e.getMessage() );

//                        }finally {
//                            retriever.release();
//
//                            cover = d.folderPath + d.fileName?.split(".")?.get(0) + "_cover.jpg"
//
//                        }
                        val bitmap =
                            ThumbnailUtils.createVideoThumbnail(d.filePath, MINI_KIND);
                        d.folderPath?.let { bitmap?.saveTo(it, d.fileName?.split(".")?.get(0) + "_cover.jpg") }
                        cover = d.folderPath +
                                "/"+ d.fileName?.split(".")?.get(0) + "_cover.jpg"

                    } else {
                        cover = d.filePath ?: ""

                    }


                    val isVideo = d.isVideo
                    val url =
                        if (isVideo)
                            d.filePath ?: ""
                        else
                            d.filePath ?: ""

                    val picture = Picture(url, cover, isVideo)
                    this@AnnexAdapter.addData(picture)

                    // 检测最大附件上传数
                    if (this@AnnexAdapter.itemCount - 1 >= maxSize)
                        setShowAddItem(false)

                }
            }


        }*/
    }

}